package com.itheima.order.util;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedissonLockDemo {

    @Autowired
    RedissonClient redissonClient;

    //Ver .01
//    public Boolean addLock(String lockKey){
//        if (null==redissonClient){
//            return false;
//        }
//        //获取锁对象
//        RLock lock = redissonClient.getLock(lockKey);
//        try{
//            //加锁 锁的时长为30秒
//            lock.lock(30, TimeUnit.SECONDS);
//            System.out.println("线程 "+Thread.currentThread().getId() + " 获取到锁");
//            return true;
//        }catch (Exception e){
//            System.out.println("获取锁失败");
//            return false;
//        }
//    }


    //Ver .02 看门狗机制
    public Boolean addLock(String lockKey){
        if (null==redissonClient){
            return false;
        }
        //获取锁对象
        RLock lock = redissonClient.getLock(lockKey);
        try{
            //加锁 锁的时长为30秒
//            lock.lock(30, TimeUnit.SECONDS);
            //尝试获取锁的时间为30s
            lock.tryLock(30,TimeUnit.SECONDS);
            System.out.println("线程 "+Thread.currentThread().getId() + " 获取到锁");
            return true;
        }catch (Exception e){
            System.out.println("获取锁失败");
            return false;
        }
    }

    public Boolean releaseLock(String lockKey){
        RLock lock = redissonClient.getLock(lockKey);

        try {
            lock.unlock();
            System.out.println("线程 "+Thread.currentThread().getId() + " 解锁");
            return true;
        }catch (Exception e){
            System.out.println(e.getMessage());
            return false;
        }
    }

}
